package gameoflife;

import java.util.ArrayList;
import java.util.List;

public class Grid {

	private static final int MAX_NUMBER_OF_NEIGHBOURS = 8;
	private final int rows;
	private final int columns;
	private final Cell[][] cells;

	public Grid(int rows, int columns) {
		this.rows = rows;
		this.columns = columns;
		cells = new Cell[rows][columns];
	}

	public int rows() {
		return rows;
	}

	public int columns() {
		return columns;
	}

	public void addCells(Cell... cells) {
		for (Cell cell : cells) {
			this.cells[cell.x()][cell.y()] = cell;
		}
	}

	public List<Cell> getNeighboursForCell(Cell cell) {
		int x = cell.x();
		int y = cell.y();
		List<Cell> neighbours = new ArrayList<>(MAX_NUMBER_OF_NEIGHBOURS);
		for (int row = x - 1; row <= x + 1; row++)
			for (int column = y - 1; column <= y + 1; column++)
				if (cell.isNeighbourOf(row, column)
						&& isInGridBoundaries(row, column))
					neighbours.add(cells[row][column]);

		return neighbours;
	}

	private boolean isInGridBoundaries(int row, int column) {
		return isInHorizontalGridBoundaries(row)
				&& isInVerticalGridBoundaries(column);
	}

	private boolean isInHorizontalGridBoundaries(int row) {
		return row >= 0 && row < rows;
	}

	private boolean isInVerticalGridBoundaries(int column) {
		return column >= 0 && column < columns;
	}

	public Cell getCellAt(int x, int y) {
		return cells[x][y];
	}

}